require('dotenv').config();
const mysql = require('mysql2/promise');

(async()=>{
  const conn = await mysql.createConnection({
    host: process.env.DB_HOST || '127.0.0.1',
    port: Number(process.env.DB_PORT || 3306),
    user: process.env.DB_USER || 'root',
    password: process.env.DB_PASS || '',
    database: process.env.DB_NAME || 'rainng_course',
  });
  try {
    // 1) 确保 /admin/stats 权限存在
    const [rows] = await conn.execute("SELECT right_id FROM rs_right WHERE right_api='/admin/stats'");
    let rightId = rows[0]?.right_id;
    if(!rightId){
      // 借用管理员首页图标（right_id=3）
      const [iconRows] = await conn.execute("SELECT right_icon FROM rs_right WHERE right_id=3");
      const icon = iconRows[0]?.right_icon || '';
      const [ins] = await conn.execute(
        "INSERT INTO rs_right (right_name,right_api,right_path,right_icon,right_level,right_function) VALUES (?,?,?,?,?,?)",
        ['系统统计','/admin/stats','/home/admin/welcome', icon, 0, JSON.stringify([1])]
      );
      rightId = ins.insertId;
      console.log('[patch] inserted rs_right /admin/stats =>', rightId);
    } else {
      console.log('[patch] rs_right /admin/stats exists =>', rightId);
    }

    // 2) 授权给管理员角色（role_id=2），功能码 GET=1
    const [rr] = await conn.execute(
      "SELECT 1 FROM rs_role_right WHERE role_id=2 AND right_id=?",
      [rightId]
    );
    if(rr.length===0){
      await conn.execute(
        "INSERT INTO rs_role_right (role_id,right_id,right_function) VALUES (?,?,?)",
        [2, rightId, 1]
      );
      console.log('[patch] grant /admin/stats to role_id=2');
    } else {
      console.log('[patch] role_id=2 already granted /admin/stats');
    }
  } finally {
    await conn.end();
  }
})().catch(e=>{ console.error('[patch] error:', e.message); process.exit(1); });
